var newBidsAjax,newBidAjax;
var newBidsArr = [];
var lastBidPublishTime;

//gets new Bids from the server 
function getNewBids(){
	if(!isLogged)
		return;
	var url = insertParam("Bids", "startFrom", lastBidPublishTime);
	newBidsAjax = fire("GET", url, null, newBidsListener);
}


//stores the new Bids in the server as well as it calls the UI updater
function newBidsListener(){
	var obj = validResponse(newBidsAjax);
	if (obj != undefined && obj.bids != null && obj.bids.length > 0){
		for(var i = obj.bids.length - 1; i > -1; i--){
			newBidsArr.unshift(obj.bids[i]);
		}
		lastBidPublishTime = obj.bids[0].time;
	fetchNewBids(obj.bids);
	}
}

// store the publish time of the most new item we are showing 


var newBidsCheckingInterval,updateBidsInterval;

function startRefreshingBids(){
// every 5 seconds check for new Bids
	getNewBids();
	newBidsCheckingInterval = setInterval(getNewBids, 5000);
	updateBids();
	updateBidsInterval = setInterval(updateBids, 5000);

}

function stopRefreshingBids(){
	clearInterval(newBidsCheckingInterval);
	clearInterval(updateBidsInterval);

}

//posting a new item
function newBid(params){
	newBidAjax = fire("POST","Bids",params,placeBidListener);
}

function placeBidListener(){
	var obj = validResponse(newBidAjax);
	if (obj != undefined){
		if(obj.result == true){
			selectedItem.currentBidAmount = obj.newCurrentBidAmount;
			updateCurrentItem();
		}else{
			showError(obj.errorMessage);
		}
	}
}

function getIsNotOverBidsIDs(){
var result = [];
	for(var i = 0; i < newBidsArr.length; i++){
		if(newBidsArr[i].sellTime <= new Date().getTime()){
			newBidsArr[i].ifOver = true;
			if(userName == newBidsArr[i].winnerUserName)
				newBidsArr[i].ifWon = true;
		}else{
			result.push(newBidsArr[i].itemID);
		}
		}
	return result;
}

function updateBids(){
		var itemsIDs;
		itemsIDs = getIsNotOverBidsIDs();
		if(itemsIDs.length < 1 || !isLogged){
			updateBidsTable();
			return;
		}
		var url = "Items?itemsToUpdate=" + JSON.stringify(itemsIDs);
		  fire("GET", url, null,
				updateBidsListener);	
}

function updateBidsListener(){
	var obj = validResponse(this);
	if (obj != undefined && obj.updatedItems != null && obj.updatedItems.length != null) {
		var stillBidsCounter = 0;
		for(var i = 0; i < newBidsArr.length; i++){
			if(!newBidsArr[i].ifOver && obj.updatedItems[stillBidsCounter] != null ){
				newBidsArr[i].winnerUserName = obj.updatedItems[stillBidsCounter++].winnerUserName;
			}else{
			continue;	
			}
			}
		updateBidsTable();
	}
}


function emptyCachedBids(){
	emptyContainer(getBidsTableBody());
	lastBidPublishTime = null;
	newBidsArr.length = 0;
}

setTimeout(function(){startRefreshingBids();}, 50);

